package com.ljx.qqpro.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.ljx.qqpro.common.exception.MyException;
import com.ljx.qqpro.common.utils.JwtUtil;
import com.ljx.qqpro.vo.user.LogUserVo;
import com.ljx.qqpro.vo.user.RegUserVo;
import org.springframework.stereotype.Service;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ljx.qqpro.common.utils.PageUtil;
import com.ljx.qqpro.common.utils.Query;

import com.ljx.qqpro.dao.UserDao;
import com.ljx.qqpro.entity.UserEntity;
import com.ljx.qqpro.service.UserService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;


@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {

    @Override
    public PageUtil queryPage(Map<String, Object> params) {
        IPage<UserEntity> page = this.page(
                new Query<UserEntity>().getPage(params),
                new QueryWrapper<UserEntity>()
        );

        return new PageUtil(page);
    }

    @Override
    public String login(LogUserVo logUserVo) {

        UserEntity userEntity = baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("username", logUserVo.getUsername()).eq("status", 1));
        String password = DigestUtils.md5DigestAsHex(logUserVo.getPassword().getBytes());
        if(userEntity == null || !password.equals(userEntity.getPassword())){
            throw new MyException("账号或者密码错误");
        }

        return JwtUtil.createToken(userEntity.getId(), userEntity.getUsername());
    }

    @Transactional
    @Override
    public void register(RegUserVo regUserVo) {

        if(!regUserVo.getPassword().equals(regUserVo.getPassword2())){
            throw new MyException("两次密码输入不一致");
        }

        UserEntity userEntity = baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("username", regUserVo.getUsername()).eq("status", 1));
        if(userEntity != null){
            throw new MyException("用户已经存在");
        }

        userEntity = BeanUtil.copyProperties(regUserVo, UserEntity.class);
        userEntity.setNickname("小Q");
        userEntity.setPassword(DigestUtils.md5DigestAsHex(userEntity.getPassword().getBytes()));
        userEntity.setAvatar("https://q1.qlogo.cn/g?b=qq&nk=2770063826&s=100");
        baseMapper.insert(userEntity);

    }

    @Override
    public UserEntity getUserInfo(String username) {
        return this.baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("username", username).eq("status", 1));
    }
}